package com.ruoyi.web.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.domain.WorkForm;
import com.ruoyi.web.domain.dto.GangdanAppraiseParamDto;
import com.ruoyi.web.domain.dto.GongdanConfirmParamDto;
import com.ruoyi.web.domain.vo.GangdanAppraiseVo;
import com.ruoyi.web.domain.vo.GongdanConfirmVo;
import com.ruoyi.web.domain.vo.LargeScreenDataVo;
import com.ruoyi.web.domain.vo.PieChartVo;
import com.ruoyi.web.mapper.GangDanConfirmMapper;
import com.ruoyi.web.service.GangDanConfirmAndAppraiseService;
import com.ruoyi.web.service.WorkFormService;
import com.ruoyi.websocket.WebSocketManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @description: GangDanConfirmAndAppraiseImpl
 * @auth fcb
 * @date 2025-03-10 15:58
 **/
@Service
@Slf4j
public class GangDanConfirmAndAppraiseImpl implements GangDanConfirmAndAppraiseService {

    // 驳回状态
    private static final String BACK = "2";
    // 完成状态
    private static final String COMPLETE = "3";

    // 诉求状态处理中
    private static final int WORK_FORM_STATUS_DEALING = 1;
    // 诉求状态完成，但是待评价
    private static final int WORK_FORM_STATUS_FINISH = 2;
    // 诉求评价完毕
    private static final int WORK_FORM_STATUS_EVA_FINISH = 3;

    @Autowired
    private GangDanConfirmMapper gangDanConfirmMapper;

    @Autowired
    private WorkFormService workFormService;

    /**
     * 设置诉求的确认信息.
     * 3完成：完成状态可进行下一步诉求评价
     * 2驳回：需要把诉求处理的页面字段设置为空
     * 1延期：仅记录数据
     * 0挂起：仅记录数据
     *
     * @param paramDto 确认参数
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateGongDanConfirm(GongdanConfirmParamDto paramDto) {
        this.checkParam(paramDto);
        Integer workFromStatus = gangDanConfirmMapper.queryWorkFromStatus(paramDto.getBaseId());
        // 诉求状态不是处理中
        if(workFromStatus == null || workFromStatus != WORK_FORM_STATUS_DEALING) {
            throw new RuntimeException("该诉求状态不是处理中，无法确认");
        }
        // 诉求的确认状态是驳回，则将上一步填写的表单设置为null
        if(BACK.equals(paramDto.getCompleteConfirmation())) {
            // 更新诉求处理页面字段为null
            gangDanConfirmMapper.backGongDanConfirm(paramDto.getBaseId());
        }
        gangDanConfirmMapper.updateGangDanConfirm(paramDto);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void addGongDanAppraise(GangdanAppraiseParamDto paramDto) {
        if(paramDto.getBaseId() == null || StringUtils.isEmpty(paramDto.getEvaluationConfirmation())) {
            throw new RuntimeException("添加诉求评价，参数错误");
        }
        Integer orderStatus = gangDanConfirmMapper.queryWorkFromStatus(paramDto.getBaseId());
        if(WORK_FORM_STATUS_FINISH != orderStatus) {
            throw new RuntimeException("该诉求不是处理完成状态，无法评价");
        }
        if(StringUtils.isEmpty(paramDto.getEvaluationTime())) {
            paramDto.setEvaluationTimeTransform(new Date());
        }else {
            Date date = DateUtils.parseDate(paramDto.getEvaluationTime());
            paramDto.setEvaluationTimeTransform(date);
        }
        gangDanConfirmMapper.addGangDanAppraise(paramDto);
        // 修改诉求状态为完成
        gangDanConfirmMapper.updateWorkFormStatus(paramDto.getBaseId(), WORK_FORM_STATUS_EVA_FINISH);

        //将最新大屏数据推送给前端(位于city)
        WorkForm workForm = workFormService.getById(paramDto.getBaseId());
        String province = workForm.getProvince();
        String city = workForm.getCity();
        LargeScreenDataVo largeScreenDataVo = new LargeScreenDataVo();
        List<PieChartVo> serviceStatesCount = workFormService.getServiceStatesCount(province, city, null);
        List<PieChartVo> enterpriseSatisfactionRatio = workFormService.getEnterpriseSatisfactionRatio(province, city, null);
        largeScreenDataVo.setServiceState(serviceStatesCount);
        largeScreenDataVo.setEnterpriseSatisfaction(enterpriseSatisfactionRatio);
        Gson gson1 = new GsonBuilder().serializeNulls().create();
        String largeScreenDataResultJson1 = gson1.toJson(largeScreenDataVo);
        Set<String> sessionKeys1 = WebSocketManager.getSessionKeysByArea(city);
        for (String sessionKey : sessionKeys1) {
            WebSocketManager.sendMessageToKey(sessionKey, largeScreenDataResultJson1);
        }

        //将最新大屏数据推送给前端(位于province)
        LargeScreenDataVo largeScreenDataVo1 = new LargeScreenDataVo();
        List<PieChartVo> serviceStatesCount1 = workFormService.getServiceStatesCount(province, null, null);
        List<PieChartVo> enterpriseSatisfactionRatio1 = workFormService.getEnterpriseSatisfactionRatio(province, null, null);
        largeScreenDataVo1.setServiceState(serviceStatesCount1);
        largeScreenDataVo1.setEnterpriseSatisfaction(enterpriseSatisfactionRatio1);
        Gson gson2 = new GsonBuilder().serializeNulls().create();
        String largeScreenDataResultJson2 = gson2.toJson(largeScreenDataVo1);
        Set<String> sessionKeys2 = WebSocketManager.getSessionKeysByArea(province);
        for (String sessionKey : sessionKeys2) {
            WebSocketManager.sendMessageToKey(sessionKey, largeScreenDataResultJson2);
        }
    }

    /**
     * 根据诉求id查询诉求确认信息
     *
     * @param baseId
     * @return
     */
    @Override
    public GongdanConfirmVo queryGongDanConfirmVoById(Long baseId) {
        if(baseId == null) {
            throw new RuntimeException("参数错误");
        }
        GongdanConfirmVo gongdanConfirmVo = gangDanConfirmMapper.queryGongDanConfirmVoById(baseId);
        gongdanConfirmVo.setCompleteConfirmation(GongdanConfirmVo.transformCompleteConfirmation(gongdanConfirmVo.getCompleteConfirmation()));
        return gongdanConfirmVo;
    }

    /**
     * 根据诉求id查询诉求评价信息
     *
     * @param baseId
     * @return
     */
    @Override
    public GangdanAppraiseVo queryGangDanAppraiseVoById(Long baseId) {
        if(baseId == null) {
            throw new RuntimeException("参数错误");
        }
        return gangDanConfirmMapper.queryGangDanAppraiseVoById(baseId);
    }

    private void checkParam(GongdanConfirmParamDto paramDto) {
        if(paramDto.getBaseId() == null) {
            log.error("确认诉求时，诉求id为空");
            throw new RuntimeException("确认诉求时，诉求id为空");
        }
        if(StringUtils.isEmpty(paramDto.getCompleteConfirmation())) {
            log.error("确认诉求时，确认状态为空.诉求id：{}", paramDto.getBaseId());
            throw new RuntimeException("确认诉求时，确认状态为空");
        }
    }
}
